package com.ydl.shopping.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ydl.shopping.core.entity.LoginUser;
import com.ydl.shopping.domain.TbUser;
import com.ydl.shopping.security.context.LoginUserContextHolder;
import com.ydl.shopping.service.ITbUserService;
import com.ydl.shopping.utils.CacheUtil;
import com.ydl.shopping.utils.web.TokenService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.ydl.shopping.constant.RedisConstants.LOGIN_KEY;
import static com.ydl.shopping.constant.RedisConstants.LOGIN_KEY_TTL;
import static com.ydl.shopping.constant.SystemConstants.AUTHORIZATION;

/**
 * 认证过滤器（是否登录）
 *
 * @author 林武泰
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private TokenService tokenService;

    @Resource
    private ITbUserService sysUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的token
        String token = request.getHeader(AUTHORIZATION);

        // 获取用户id
        Long userId = tokenService.getUserId(token);
        if (userId == 0) {
            // 未通过，则直接放行
            filterChain.doFilter(request, response);
            return;
        }

        String securityKey = LOGIN_KEY + userId + ":" + token;

        // 从redis中获取登录用户相关信息
        String result = cacheUtil.getStr(LOGIN_KEY + userId + ":" + token);

        // 判断登录用户信息是否为空
        if (StrUtil.isBlank(result)) {
            // 删除用户信息
            cacheUtil.delete(securityKey);
            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 将json格式转为bean
        LoginUser loginUser = JSONUtil.toBean(result, LoginUser.class);

        // 更新用户信息
        TbUser sysUser = sysUserService.getById(userId);
        loginUser.setTbUser(sysUser);

        // 封装authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        LoginUserContextHolder.setContext(loginUser);
        // 刷新登录用户相关信息有效期
        cacheUtil.expire(securityKey, LOGIN_KEY_TTL, TimeUnit.MINUTES);

        // 放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }
}
